//
//  SLNetWork.m
//  StarLight
//
//  Created by 吴涛 on 16/5/9.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLNetWork.h"
#import "Reachability.h"

@interface SLNetWork ()


@end



@implementation SLNetWork


+ (void)getDataWithRequest:(NSString *)request complete:(completeBlock)complete{
  
  [SVProgressHUD showWithStatus:@"正在加载"];
  
  Reachability *reach = [self netReach];
  if (reach.isReachable) {
    
    AFHTTPSessionManager *manager = [self manager];
    NSDictionary *dic = [DEFAULTS objectForKey:loginInfo];
    
    NSString *newRequst = [NSString stringWithFormat:@"%@&auth_token=%@",request,dic[@"auth_token"]];
    
    NSLog(@"%@",newRequst);
    
    [manager GET:newRequst parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {}
         success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
           NSDictionary *respondse = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
           if ([respondse[@"success"] isEqual:@1]) {
             complete(respondse, nil);
             [SVProgressHUD dismiss];
           }else{
             [SVProgressHUD showErrorWithStatus:respondse[@"result"]];
           }
           
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           NSLog(@"%@",error);
           [SVProgressHUD showErrorWithStatus:@"请求出错，请检查网络"];
           complete(nil, error);
         }];

  }else{
    
    [SVProgressHUD showErrorWithStatus:@"无网络连接"];
  }
  
  
}

+ (void)postDataWithParameters:(id)parameters postUrl:(NSString *)postUrl complete:(completeBlock)complete{
  [SVProgressHUD showWithStatus:@"正在加载"];
  Reachability *reach = [self netReach];
  if (reach.isReachable) {
  
  AFHTTPSessionManager *manager = [self manager];
    
  NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:parameters];
  
  NSString *token = [DEFAULTS objectForKey:loginInfo][@"auth_token"];
  
  if (![postUrl isEqualToString:[NSString backUrlWithService:@"user" methodName:@"login"]]) {
    [dic setObject:token forKey:@"auth_token"];
  }
    
  [manager POST:postUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    
  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSDictionary *respondse = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    
    if ([respondse[@"success"] isEqual:@1]) {
      complete(respondse, nil);
    }else{
      [SVProgressHUD showImage:nil status:respondse[@"result"]];
    }
    

    
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"%@",error);
    
    [SVProgressHUD showErrorWithStatus:@"请求出错，请检查网络"];
    complete(nil, error);
  }];
  }else{
    [SVProgressHUD showErrorWithStatus:@"无网络连接"];
  }
}

+ (void)uploadFileWithFileArr:(NSArray *)fileArr
        andFileInformationArr:(NSArray *)infoArr
                   andPostUrl:(NSString *)postUrl
                andParameters:(id)parameters
                     complete:(completeBlock)complete{
  
  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",nil];
  
  
  
  NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:parameters];
  
  NSString *token = [DEFAULTS objectForKey:loginInfo][@"auth_token"];
  
  [dic setObject:token forKey:@"auth_token"];

  
  [manager POST:postUrl parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    if (fileArr.count > 1) {
      [formData appendPartWithFileData:fileArr[1] name:@"headPhoto" fileName:@"headPhoto.jpg" mimeType:@"image/jpeg"];
    }
  } progress:^(NSProgress * _Nonnull uploadProgress) {
    
  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    if (responseObject[@"success"]) {
      complete(responseObject, nil);
    }else{
      [SVProgressHUD showErrorWithStatus:responseObject[@"result"]];
    }

  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"%@",error);
    [SVProgressHUD showErrorWithStatus:@"请求出错，请检查网络"];
    complete(nil, error);
  }];
  
}



+ (void)upLoadImage:(NSData *)image sender:(NSString *)sender sendeName:(NSString *)sendeName complete:(completeBlock)complete{
  //headPhoto
    //userimage
  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",nil];
  
  NSString *postUrl = [NSString backUrlWithService:@"user" methodName:sendeName];
  NSDictionary *parameters = @{@"uid":[DEFAULTS objectForKey:loginInfo][@"id"],@"auth_token":[DEFAULTS objectForKey:loginInfo][@"auth_token"],sender : image};
  
  
  [manager POST:postUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    [formData appendPartWithFileData:image name:@"headPhoto" fileName:@"headPhoto.jpg" mimeType:@"image/jpeg"];
  } progress:^(NSProgress * _Nonnull uploadProgress) {
    
  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    if (responseObject[@"success"]) {
      complete(responseObject, nil);
    }else{
      [SVProgressHUD showErrorWithStatus:responseObject[@"result"]];
    }
    
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"%@",error);
    [SVProgressHUD showErrorWithStatus:@"请求出错，请检查网络"];
    complete(nil, error);
  }];

}




+(AFHTTPSessionManager *)manager{
  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  // 超时时间
  manager.requestSerializer.timeoutInterval = kTimeOutInterval;
  // 声明上传的是json格式的参数，需要你和后台约定好，不然会出现后台无法获取到你上传的参数问题
  manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 上传普通格式
  // 声明获取到的数据格式
  manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  return manager;
}

+ (NSString *)backUid{
  NSDictionary *dic = [DEFAULTS objectForKey:@"loginInformation"];
  return dic[@"id"];
  
}



+ (Reachability *)netReach{
  
    Reachability *netReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
  
  return netReach;
}


@end



@implementation NSString (NetWork)

+ (NSString *)backUrlWithService:(NSString *)service methodName:(NSString *)methodName{
  
  NSString *url = [NSString stringWithFormat:@"%@/%@/%@",baseUrl,service,methodName];
  
  return url;
}

@end




